#include "DetectPlate.h"
#include "logger.h"

DetectPlate::DetectPlate()
{
}


DetectPlate::~DetectPlate()
{
}

int DetectPlate::init()
{
	YoloParam param;
	param.confidence_threshold = conf_thre;
	param.score_threshold = score_thre;
	param.nms_threshold = nms_thre;

	return 	detecter.init(modle_path, class_path, param, true);
}


int DetectPlate::get_best_reslut(cv::Mat img, YoloDetection& best_reslut)
{
    std::vector<YoloDetection> detect_output;
    detecter.detect(img, detect_output);

    YoloDetection best_plate = { 0,0,{ 0,0,0,0 } };
    float max_confidence = 0;

    if (detect_output.size() == 1){
        best_plate.box = detect_output.at(0).box;
        best_plate.class_id = detect_output.at(0).class_id;
        best_plate.confidence = detect_output.at(0).confidence;
    }else if (detect_output.size() > 1)
    {
        max_confidence = detect_output.at(0).confidence;
        best_plate.box = detect_output.at(0).box;
        best_plate.class_id = detect_output.at(0).class_id;
        best_plate.confidence = detect_output.at(0).confidence;

        for (int i = 1; i < detect_output.size(); i++){
            if (max_confidence < detect_output.at(i).confidence){
                max_confidence = detect_output.at(i).confidence;
                best_plate.box = detect_output.at(i).box;
                best_plate.class_id = detect_output.at(i).class_id;
                best_plate.confidence = detect_output.at(i).confidence;
            }
        }
    }else{
        std::cout << " YOLO detection failed! " << std::endl;
        return -1;
    }

    std::cout << " max_confidence is: " << max_confidence << std::endl;
    std::cout << "best_plate box is: " << best_plate.box << std::endl;
    std::cout << "best_plate class is:  " << best_plate.class_id << std::endl;
    std::cout << "best_plate confidence is: " << best_plate.confidence << std::endl;

    //判断box尺寸 若box  width height 过小则认为检测失败
    if (best_plate.box.width < 10 && best_plate.box.height < 10)
    {
        std::cout << "YOLO detection result box size is too small may it wrong!" << std::endl;
        return -1;
    }

    best_reslut = best_plate;
    return 0;
}

